package com.bjpowernode.springboot.service.impl;

import com.bjpowernode.springboot.mapper.StudentMapper;
import com.bjpowernode.springboot.model.Student;
import com.bjpowernode.springboot.service.StudentService;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
@DubboService(interfaceName = "com.bjpowernode.springboot.service.StudentService",
              version = "1.0.0",
              timeout = 15000)
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;

    @Override
    public Student queryStudentById(Integer id) {

        return studentMapper.selectByPrimaryKey(id);
    }

    @Override
    public Integer queryStudentCount(){

        Integer studentCount=(Integer) redisTemplate.opsForValue().get("studentCount");

        if(null==studentCount) {
            //redis中没有，则去数据库中查询
            studentCount = studentMapper.selectStudentCount();

            //将查询得到的结果放入redis缓存,并设置该数据的存在时间为30s
            redisTemplate.opsForValue().set("studentCount",studentCount,30, TimeUnit.SECONDS);
        }
        return studentCount;
    }
}
